package leetcode.ge100;

import leetcode.lt100.TreeNode;

import java.util.HashMap;

class Solution_105 {



    public static void main(String[] args) {
        int[] preorder = {3, 9, 20, 15, 7};
        int[] inorder = {9, 3, 15, 20, 7};
        new Solution_105().buildTree(preorder, inorder);
    }


    public TreeNode buildTree(int[] preorder, int[] inorder) {
        HashMap<Integer, Integer> idxMap = new HashMap<Integer, Integer>();
        int length = inorder.length;
        for (int i = 0; i < length; i++)
            idxMap.put(inorder[i], i);
        return buildTree(preorder, inorder, 0, length, 0, length, idxMap);
    }

    private TreeNode buildTree(int[] preorder, int[] inorder, int inStart, int inEnd, int preStart, int preEnd, HashMap<Integer, Integer> idxMap) {
        if (preStart >= preEnd) {
            return null;
        }
        int rootVal = preorder[preStart];
        TreeNode root = new TreeNode(rootVal);
        Integer inIndex = idxMap.get(rootVal);
        int leftNum = inIndex - inStart;
        root.left = buildTree(preorder, inorder, inStart, inIndex, preStart + 1, preStart + 1 + leftNum, idxMap);
        root.right = buildTree(preorder, inorder, inIndex + 1, inEnd, preStart + 1 + leftNum, preEnd, idxMap);
        return root;
    }

}